package com.yjj.demo.thread.service;

import com.yjj.demo.thread.task.ThreadTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 *
 *
 * @author yangjiajia
 * @time 2022/3/20 18:30
 */
@Service
public class ThreadPoolService {

    private Logger logger = LoggerFactory.getLogger(ThreadPoolService.class);

    private ScheduledExecutorService scheduledExecutorService;

    private Map<Integer, Integer> taskMap = new HashMap<>();
    private int currentTaskId = 1;
    private int lastTaskId = 2;

    private Map<Integer, ScheduledFuture> taskSchedule = new ConcurrentHashMap<>();

    public ThreadPoolService() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        //scheduledExecutorService = new ScheduledThreadPoolExecutor(1, new BasicThread);

        taskMap.put(1, 1);
        taskMap.put(2, 2);
        taskMap.put(3, 3);
        taskMap.put(4, 3);

        lastTaskId = 3;
    }

    @PostConstruct
    public void init() {
        logger.info("task init");

        nextTask(currentTaskId);
    }

    public void nextTask(int taskId) {

        if (!taskMap.containsKey(taskId)) {
            logger.info("任务执行结束");
            return;
        }

        long time = taskMap.get(taskId);

        ScheduledFuture result = scheduledExecutorService.schedule(new ThreadTask(taskId, this), time, TimeUnit.MINUTES);
        taskSchedule.put(taskId, result);

        currentTaskId ++;
    }

    public void task(int taskId) {

        long time = taskMap.get(taskId);

        ScheduledFuture result = scheduledExecutorService.schedule(new ThreadTask(taskId, this), time, TimeUnit.MINUTES);
        taskSchedule.put(taskId, result);
    }

    public void cancel(int taskId) {
        logger.info("取消任务,taskId:{}", taskId);
        if (!taskSchedule.containsKey(taskId)) {
            return;
        }
        ScheduledFuture future = taskSchedule.get(taskId);
        future.cancel(true);

        taskId ++;
        nextTask(taskId);
    }

}
